import React, { useState, useEffect, useMemo } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Typography,
  Notification,
} from '@arco-design/web-react';
import PermissionWrapper from '@/components/PermissionWrapper';
import { IconPlus } from '@arco-design/web-react/icon';
import useLocale from '@/utils/useLocale';
import SearchForm from './form';
import locale from './locale';
import styles from './style/index.module.less';
import { DefaultSorter, getColumns } from './constants';
import { getDictPage, removeDict } from '@/api/dict';

import { v4 } from 'uuid';
import AddPage from './addPage';
import UpdatePage from './updatePage';
import { Grid } from '@arco-design/web-react';
import DictGroup from './group';
const Row = Grid.Row;
const Col = Grid.Col;

const { Title } = Typography;

function SearchTable() {
  const t = useLocale(locale);

  //表格列回调函数
  const tableCallback = async (record, type) => {
    //新增
    if (type === 'add') {
      addData();
    }
    //编辑
    if (type === 'update') {
      updateData(record.id);
    }
    //删除
    if (type === 'delete') {
      deleteData(record.id);
    }
    //点击分组
    if (type === 'onClickGroup') {
      onClickGroup(record);
    }
  };

  //添加
  const [addVisible, setAddVisible] = useState(false);
  function addData() {
    if (currentGroupId == undefined) {
      Notification.warning({
        content: t['searchForm.id.placeholdergroup'],
        duration: 1000,
      });
      return;
    }
    setAddVisible(true);
  }

  //编辑
  const [updateVisible, setUpdateVisibled] = useState(false);
  const [updateInfoId, setUpdateInfoId] = useState();
  function updateData(id) {
    setUpdateInfoId(id);
    setUpdateVisibled(true);
  }

  //删除
  function deleteData(id) {
    removeDict(id).then((res) => {
      const { success, message } = res.data;
      if (success) {
        Notification.success({ content: message, duration: 1000 });
        fetchData(currentGroupId);
      } else {
        Notification.error({ content: message, duration: 1000 });
        fetchData(currentGroupId);
      }
    });
  }

  //点击分组
  const [currentGroupId, seCurrentGroupId] = useState(undefined);

  function onClickGroup(id) {
    seCurrentGroupId(id);
    fetchData(id);
  }

  const columns = useMemo(() => getColumns(t, tableCallback), [t]);

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [sorter, setSorter] = useState(DefaultSorter);
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState<any>({});
  const [searchId, setSearchId] = useState<string>('');

  useEffect(() => {
    fetchData(currentGroupId);
  }, [
    pagination.current,
    pagination.pageSize,
    JSON.stringify(sorter),
    JSON.stringify(formParams),
    searchId,
  ]);

  //分页请求
  function fetchData(group_id) {
    if (group_id == undefined) {
      setLoading(false);
      return;
    }
    const { current, pageSize } = pagination;
    setLoading(true);
    getDictPage({
      page_data: {
        page: current,
        page_size: pageSize,
        sorter,
      },
      group_id: group_id,
      ...formParams,
    }).then((res) => {
      const { total, record } = res.data.data;
      setData(record);
      setPatination({
        ...pagination,
        current,
        pageSize,
        total: total,
      });
      setLoading(false);
    });
  }

  //表格分页回调
  function onChangeTable({ current, pageSize }, { field, direction }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });

    if (direction == undefined) {
      setSorter(undefined);
    } else {
      setSorter({
        field,
        direction: direction === 'ascend' ? 'asc' : 'desc',
      });
    }
  }

  //搜索表单回调
  function handleSearch(params) {
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
    setSearchId(v4());
  }

  return (
    <Row>
      <Col span={6} style={{ marginRight: 16, height: '100%' }}>
        <DictGroup callback={tableCallback} />
      </Col>
      <Col span={17}>
        <Card>
          <Title heading={6}>{t['menu.list.searchTable']}</Title>
          <SearchForm onSearch={handleSearch} />
          <Row>
            <Col>
              <PermissionWrapper
                requiredPermissions={[
                  { resource: 'dict_manager', actions: ['api_dict_add'] },
                ]}
              >
                <div className={styles['button-group']}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<IconPlus />}
                      onClick={() => tableCallback(null, 'add')}
                    >
                      {t['searchTable.operations.add']}
                    </Button>
                  </Space>
                </div>
              </PermissionWrapper>
            </Col>
          </Row>

          <Table
            rowKey="id"
            loading={loading}
            onChange={onChangeTable}
            pagination={pagination}
            columns={columns}
            data={data}
          />

          <AddPage
            currentGroupId={currentGroupId}
            visible={addVisible}
            setVisible={setAddVisible}
            callback={() => fetchData(currentGroupId)}
          />
          <UpdatePage
            id={updateInfoId}
            visible={updateVisible}
            setVisible={setUpdateVisibled}
            callback={() => fetchData(currentGroupId)}
          />
        </Card>
      </Col>
    </Row>
  );
}

export default SearchTable;
